$(function () {

    // 输入框
    $("#invest_money").bind(input_key, function () {
        checkInvestMoney();
    });

    //选择红包
    $(".envelopes-list ul li").click(function () {
        if (!$(this).is(".over")) {
            var parent = $(this).find(".data");
            var money = parseFloat($("#invest_money").val()) ? parseFloat($("#invest_money").val()) : '0';
            var money_limit = parseFloat(parent.attr('data-limitmoney'));
            if (money < money_limit) {
                alertcouponlimit(money_limit, parent);
            }
            else {
                selectCoupon(parent);
            }
        }
    });

    $(".redPage_use_tips").bind("click", function () {
        if (notCard() === true) {
            layer.alert("暂无可以使用红包", {icon: 0});
            return false;
        }
        cardShow();
    })

});

// 收益计算公式
var calculate = function (amount, rate, time, text, month1, month2, firstDay) {  //  金额、年利率、标的时间、还款方式
    /*
        '1'=>'一次性还款',
        '2'=>'按月分期、等额本金',
        '3'=>'按月分期、等额本息',
        '4'=>'按月付息、到期还本'
     */
    var interest = 0;
    // 一次性还款
    if (text == 1 || text == 4) {
        interest = amount * (rate / 100) * (time / 360);
    }

    // 等额本金
    if (text == 2 || text == 3) {
        var ins = 0,
            times = Math.ceil(time / 30),
            lastTime = time % 30 === 0 && time !== 0 ? 30 : time % 30,
            rate2 = rate / (100 * 12);
        for (var j = 1; j < times + 1; j++) {
            if (j == 1) {
                ins += amount * lastTime * (rate2 / 30);
            } else {
                ins += ((amount - (amount / times) * (j - 1)) * rate2);
            }
        }
        interest = ins;
    }

    // 先按月付息后等额本金
    if (text == 5) {
        var month_apr = parseFloat(rate / (12 * 100));
        var day_apr = parseFloat(rate / (12 * 100 * 30));
        var first_interest = parseFloat(amount * month_apr);
        for (var i = 1; i <= month1; i++) {
            if (i == 1) {
                interest += parseFloat(amount * firstDay * day_apr);
            } else {
                interest += first_interest;
            }
        }
        var monthCapital = amount / month2;
        for (var k = 1; k <= month2; k++) {
            var second_interest = (amount - monthCapital * (k - 1)) * month_apr;
            interest += second_interest;
        }
    }

    return parseFloat(interest).toFixed(2);
};

var interestRates = function (money, time, i_day, i_rate, type, month1, month2, firstDay) { //  金额、投资时间、加息天数、加息利率、还款方式

    /*
        '1'=>'一次性还款',
        '2'=>'按月分期、等额本金',
        '3'=>'按月分期、等额本息',
        '4'=>'按月付息、到期还本'
     */

    var total = 0;
    if (isNaN(i_rate) || i_rate.length === 0) {
        i_rate = 0;
        i_day = 0;
    }

    // 一次性还款
    if (type == 1 || type == 4) {
        total = money * (i_rate / 100) * (parseInt(i_day) === 0 ? time : i_day) / 360;
    }

    // 等额本金
    if (type == 2 || type == 3) {
        if (i_day === 0) {
            var ins = 0,
                times = Math.ceil(time / 30),
                lastTime = time % 30 === 0 && time !== 0 ? 30 : time % 30,
                rate2 = i_rate / (100 * 12);
            for (var j = 1; j < times + 1; j++) {
                if (j == 1) {
                    ins += money * lastTime * (rate2 / 30);
                } else {
                    ins += ((money - (money / times) * (j - 1)) * rate2);
                }
            }
            total = ins;
        } else {
            total = money * (i_rate / 100) * i_day / 360;
        }
    }

    // 先按月付息后等额本金
    if (type == 5) {
        var month_apr = parseFloat(i_rate / (12 * 100));
        var day_apr = parseFloat(i_rate / (12 * 100 * 30));
        var first_interest = parseFloat(money * month_apr);
        for (var i = 1; i <= month1; i++) {
            if (i == 1) {
                total += parseFloat(money * firstDay * day_apr)
            } else {
                total += first_interest;
            }
        }
        var monthCapital = money / month2;
        for (var k = 1; k <= month2; k++) {
            var second_interest = (money - monthCapital * (k - 1)) * month_apr;
            total += second_interest;
        }
    }

    return parseFloat(total).toFixed(2);

};

// 投资收益计算
var calcIncome = function () {
    var repayType = parseInt($("#Repayment").val()), // 还款方式
        rate = parseFloat($("#Rate").val()), //年利率
        investMoney = parseFloat($("#invest_money").val()), //投资金额
        time = parseFloat($("#Time").val()),  // 投资时间
        day = $("#interest_day").val(),  // 加息天数
        month1 = parseInt($("#school_month1").val()),
        firstDay = parseInt($("#school_first_deadline").val()),
        month2 = parseInt($("#school_month2").val());
    var i_day = isNaN(day) || day == '' ? 0 : parseInt(day),  // 加息天数
        i_rate = parseFloat($("#interest_rate").val()),  // 加息利率
        expected = $("#expected");

    var is_newer = $("#isNewer").val() , increase = $("#newerIncrease").val() , max_increase_money = $("#newerMoney").val() ,produceType = $("#produceType").val(); // 是否是新手



    /*利息*/
    var repay_money = calculate(investMoney, rate, time, repayType, month1, month2, firstDay); //金额、年利率、标的时间、还款方式
    /*加息*/
    var interest_rates_money = interestRates(investMoney, time, i_day, i_rate, repayType, month1, month2, firstDay);//  金额、投资时间、加息天数、加息利率、还款方式
    var total = parseFloat(repay_money) + parseFloat(interest_rates_money);
    /*新手加息*/
    if(parseInt(is_newer) === 1 && parseInt(produceType) !== 6){
        var money =  investMoney <= max_increase_money ? investMoney : max_increase_money;
        var newer_interest = interestRates(money, time, 0, increase, repayType, month1, month2, firstDay);//  金额、投资时间、加息天数、加息利率、还款方式
        total = parseFloat(total) + parseFloat(newer_interest);

    }
    var new_total = parseFloat(total).toFixed(2);

    isNaN(investMoney) ? expected.html('0.00') : expected.html(new_total);
};


// 余额全投
var getAll = function () {
    var maxInput = $("#maxInvest"), invest = $("#invest_money"), need = $("#need");
    var max = parseInt(maxInput.html()), canCase = parseInt(need.html());
    invest.val(max > canCase ? canCase : max);
    checkInvestMoney();
};

// 倒计时
var countdown = function () {
    var seconds;
    var timer = null;

    function showSeconds() {
        var day1 = Math.floor(seconds / (60 * 60 * 24));
        var hour = Math.floor((seconds - day1 * 24 * 60 * 60) / 3600);
        var minute = Math.floor((seconds - day1 * 24 * 60 * 60 - hour * 3600) / 60);
        var second = Math.floor(seconds - day1 * 24 * 60 * 60 - hour * 3600 - minute * 60);
        if (day1 < 0) {
            clearInterval(timer);
            $("#loanTime").html("投标已经结束！");
            $(".investBtn").prop("disabled", true).addClass("disabled").val('已结束');
        } else {
            $("#loanTime").html(day1 + "天" + hour + "小时" + minute + "分" + second + "秒");
        }
        seconds--;
    }

    var over = $("#hid").val(); //结束的时间戳
    var now = Math.round(new Date() / 1000); //当前的时间戳
    seconds = parseInt((over - now), 10); //当前剩余时间戳
    timer = setInterval(showSeconds, 1000);
};

// 切换条点击滚动
var fixedAutoScroll = function () {
    var barOffset = $("#normal_i_bar").offset().top, documentTop = $(document).scrollTop();
    documentTop > barOffset ? $("#fixed_i_bar").show() : $("#fixed_i_bar").hide();

    $("#normal_i_bar li").each(function () {
        var id = $(this).attr("rel"), index = $(this).index();
        var thistop = $("#" + id).offset().top;
        if (documentTop >= thistop - 60) {
            $(".i_i_bar").each(function () {
                $(this).find("li").eq(index).addClass("on").siblings().removeClass("on")
            });
        }
    })
};

var checkInvestMoney = function () {
    var invest = $('#invest_money'), need = $('#need');
    var imoney = invest.val().replace(/\b(0+)/gi, '').replace(/[^\d]/gi, '').replace('/^[1-9]\d*$/', '');
    invest.val(imoney);
    if (parseFloat(invest.val()) > parseFloat(need.html())) {
        invest.val(
            parseInt(need.html())
        );
    }
    calcIncome();
};



var reCheckMoney = function (money, url) {
    if (money < invest_min) {
        layer.alert("本标最低投标金额为" + invest_min + "元",{icon : 0 , title : "温馨提醒"});
        return false;
    }
    if (money > invest_max && invest_max != 0) {
        layer.alert("本标最大投标总金额为" + invest_max + "元",{icon : 0 , title : "温馨提醒"});
        return false;
    }
    if (money > account) {
        layer.open({
            content: "尊敬的用户，您准备投标" + money + "元，但您的账户可用余额为" + account + "元，您要先去充值吗？",
            btn: ['确定', '关闭'],
            icon : 0,
            title : "温馨提醒",
            yes: function () {
                window.location.href = url;
            }
        });
        return false;
    }
    if (money > (need - invest_min) && (need - money) != 0) {
        layer.open({
            content: "最小投标金额不得低于50元，为确保满标，请输入小于或等于" + number_format(need - invest_min, 2, '.', '') + "元或直接满标。  <br/><span class='af90'>是否帮您输入 " + need + " 元进行投资？</span>",
            btn: ['确定', '关闭'],
            yes: function (index) {
                $('#invest_money').val(parseFloat(need));
                layer.close(index);
            }
        });
        return false;
    }
    return true;
};

var invest = function (param, ajaxUrl, hrefUrl) {
    $.ajax({
        url: ajaxUrl,
        type: "post",
        dataType: "json",
        data: param,
        success: function (data) {
            var norLayer = function () {
                layer.open({
                    content: data.msg,
                    btn: '我知道了'
                });
                setTimeout("window.location.reload();", 1500);
            };
            layer.closeAll();
            if (data.code == 1) {
                if($("#toInvest").length > 0){
                    showInvest(param.money);
                }else{
                    norLayer();
                }
            } else {
                norLayer();
            }
        }
    });
};


/**
 *    红包使用
 */

var alertcouponlimit = function (m, e) {
    var type = parseInt($(e).attr("data-type"));
    var t1 = (type === 2 ? '加息券' : '红包');
    var txt = '选择使用此' + t1 + '需要投资' + m + '元，当前输入投资金额不足，是否投资' + m + '元使用此' + t1 + '？';
    var couponchangemoney = function () {
        selectCoupon(e);
        $('#invest_money').val(parseFloat(m));
        calcIncome(); // 收益
        // checkInvestMoney();
    };

    layer.open({
        content: txt,
        btn: ['确定', '关闭'],
        yes: function (index) {
            couponchangemoney();
            layer.close(index);
        }
    });
};

// 显示使用红包
var selectCoupon = function (e) {
    var type = parseInt($(e).attr('data-type'));
    var text = "使用&nbsp;<span class='af00'>" + e.attr('data-money') + (type === 2 ? "</span>%&nbsp;加息券" : "</span>&nbsp;元红包");
    $('#card_id').val(
        $(e).attr('data-id')
    );
    $('#cardText').html(text);
    $(e).parents("li").addClass("on").siblings("li").removeClass("on");
    if (type === 2) {
        set_plus_input($(e).attr("data-day"), $(e).attr("data-money"));
        var div = $("#plus_txt");
        var day = $(e).attr("data-day");
        if (parseInt(day) > 0 && !isNaN(day)) {
            div.css("visibility", "visible");
        } else {
            div.css("visibility", "hidden");
        }
    } else {
        set_plus_input("", "");
    }
    calcIncome(); // 收益
    layer.closeAll();
    cardHide();
};

// 设置加息券 input
var set_plus_input = function (day, money) {
    $("#interest_day").val(day);
    $("#interest_rate").val(money);
};